<?php
//include configure file for database access
require_once 'app/configs/dbconfig.php' ;

class Access_Db extends Config_DbConfig
{
    private $DBH;
    private $STH;
    private $dbSelect;
    
    function __construct()
    {
      $this->openConnection() ;
    }
    
    private function openConnection()
    {
      try {  
       
        $this->DBH = new PDO("mysql:host=$this->host;dbname=$this->dbName", $this->user, $this->password);  
        $this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $this->DBH->exec("SET NAMES utf8");
      }  
      catch(PDOException $e) {  
          echo "Oops... " . $e->getMessage();  
      }
    }
    
    public function prepare($query)
    {
      $this->STH = $this->DBH->prepare($query);
    }
    
    public function insert($data)
    {
      try { 
        $this->STH->execute($data);
      }  
      catch(PDOException $e) {  
        echo "Oops... Data base error. " . $e->getMessage();  
        file_put_contents("logs/logs.txt", 
                $e->getMessage()."\n--------" . date("l dS of F Y h:I:s A") . "---------\n\n", 
                FILE_APPEND);  
      }
    }
    
    public function select($arr,$from,$where = NULL)
    {
      try { 
        $query = "SELECT ";
        foreach ($arr as $value) {
          $query .="$value,";
        }
        $last = strlen($query);
        $query{$last-1} = " ";
        $query .= "FROM $from ";
        if($where != NULL)
        {
          $query .="WHERE $where";
        }
        $query .= ";";
        //echo $query;
        $this->STH = $this->DBH->query($query);
        $this->STH->setFetchMode(PDO::FETCH_ASSOC);
      }  
      catch(PDOException $e) {  
        echo "Oops... Data base error. " . $query . " " . $e->getMessage();  
        file_put_contents("logs/logs.txt", 
                "\n--------" . date("l dS of F Y h:I:s A") . "---------\n" . $e->getMessage()."\n", 
                FILE_APPEND);  
      }
    }
    
    function getSpecialUserGroup($id)
    {
        $select = array(
            'user_roles.id',
            'user_roles.role_id',
            'roles.type'
        );
        $table = 'user_roles,roles';
        $where = "user_roles.user_id='$id' and user_roles.role_id=roles.id and roles.type='1'";
        $this->select($select, $table, $where);
        return $this->getSelected();
    }
    
    public function getRowCount()
    {
      return $this->STH->rowCount();
    }
    
    public function getLAstInsertedID()
    {
      return $this->DBH->lastInsertId();
    }

    public function getSelected()
    {
      return $this->STH->fetch();
    }
    
    public function execQuery($query)
    {
      $this->DBH->exec($query);
    }
    
    public function printPath()
    {
      echo $this->path;
    }
    
    public function setActive()
    {
      if($_SERVER["REQUEST_URI"] === "/")
      {
        echo "active";
      }
    }
}